package com.example.blogsystem.service;

import com.example.blogsystem.constant.Constant;
import com.example.blogsystem.mapper.BlogMapper;
import com.example.blogsystem.model.Blog;
import com.example.blogsystem.model.Result;
import com.example.blogsystem.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Service
public class BlogService {

    @Autowired
    private BlogMapper blogMapper;

    // 获取博客列表
    public List<Blog> getBlogList() {
        List<Blog> blogs = blogMapper.blogAllBlog();
        return blogs;
    }

    // 获取博客详情
    public Result<Blog> getBlogById(Integer id, HttpServletRequest request) {
        Result<Blog> result = new Result<>();
        Blog blog = blogMapper.selBlogById(id);
        if(blog == null) {
            log.error("查询不到指定博客");
            return result.fail("查询不到指定博客");
        }
        //获取token中的用户id
        String userToken = request.getHeader(Constant.USER_TOKEN);
        Integer userId = JwtUtil.getUserIdFromToken(userToken);

        if(userId == null){
            log.error("userId为空");
            return result.fail("userId为空");
        }

        // 判断用户id和当前文章的用户id是否是同一个
        if(blog.getUserId().equals (userId)) {
            blog.setLoginUser(true);
        }
        return result.success(blog);

    }

    //发布博客
    public Integer publishBlog(Blog blog) {
        return blogMapper.publishBlog(blog);
    }

    public Result<Object> deleteBlogLogic(Integer blogId) {
        Result<Object> result = new Result<>();
       log.info("delete接口,blogId:{}", blogId);
        // 1. 查询数据库中是否有该条记录
        // 2. 将该条记录的删除标志置为1
        Blog blog = blogMapper.selBlogById(blogId);
        if(blog == null) {
            log.error("数据库中没有该博客");
            return result.fail("数据库中没有该博客");
        }
        //删除博客
        Blog newBlog = new Blog();
        newBlog.setId(blogId);
        newBlog.setDeleteFlag(1);
        Integer updateRet = blogMapper.updateById(newBlog);
        if(updateRet < 1) {
            log.error("删除博客失败");
            return result.fail("删除博客失败");
        }
        log.info("删除博客成功");
        return result.success();

    }
}
